package electricity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import electricity.Enum.RepairPriorityEnum;
import electricity.Enum.RepairStatusEnum;
import electricity.domain.EquipmentRepair;
import electricity.domain.FaultAnalysis;
import electricity.domain.RepairStatusLog;
import electricity.mapper.EquipmentRepairMapper;
import electricity.mapper.FaultAnalysisMapper;
import electricity.mapper.RepairStatusLogMapper;
import electricity.service.WorkOrderService;
import electricity.vo.WorkOrder.WorkOrderDetailVO;
import electricity.vo.WorkOrder.WorkOrderListVO;
import electricity.vo.WorkOrder.WorkOrderStatusLogVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WorkOrderServiceImpl implements WorkOrderService {
    @Autowired
    private EquipmentRepairMapper repairMapper;

    @Autowired
    private RepairStatusLogMapper logMapper;

    @Autowired
    private FaultAnalysisMapper faultMapper;

    @Override
    public String createWorkOrder(Long faultId, String deviceId, Integer priority) {
        // 验证故障是否存在
        FaultAnalysis fault = faultMapper.selectById(faultId);
        if (fault == null) {
            throw new RuntimeException("故障记录不存在，无法创建工单");
        }

        // 生成工单ID（格式：WO+时间戳+随机数）
        String workOrderId = "WO" + System.currentTimeMillis() + RandomStringUtils.randomNumeric(3);

        // 创建工单
        EquipmentRepair repair = new EquipmentRepair();
        repair.setRepairId(workOrderId);
        repair.setAnomalyId(faultId);
        repair.setDeviceId(deviceId);
        repair.setRepairResult(RepairStatusEnum.PENDING.getCode());
        repair.setPriority(priority);
        repair.setCreateTime(new Date());
        repairMapper.insert(repair);


        return workOrderId;
    }

    @Override
    public boolean assignProcessor(String workOrderId, String processorId) {
        // 查询工单
        EquipmentRepair repair = getWorkOrderById(workOrderId);

      /*  // 验证工单状态（只能分配待办工单）
        if (!repair.getRepairResult().equals(RepairStatusEnum.PENDING.getCode())) {
            throw new RuntimeException("工单状态不是待办，无法分配处理人");
        }
*/
        // 更新处理人
        repair.setProcessorId(processorId);
        repairMapper.updateByPrimaryKey(repair);

       /* // 记录状态变更日志
        recordStatusLog(workOrderId, repair.getRepairResult(), repair.getRepairResult(), operatorId,
                "分配处理人：" + processorId);
*/
        return true;
    }

    @Override
    public boolean startProcessing(String workOrderId, String processorId) {
        // 查询工单
        EquipmentRepair repair = getWorkOrderById(workOrderId);

        // 验证工单状态（只能从待办开始处理）
        if (!repair.getRepairResult().equals(RepairStatusEnum.PENDING.getCode())) {
            throw new RuntimeException("工单状态不是待办，无法开始处理");
        }

        // 更新状态和开始时间
        repair.setRepairResult(RepairStatusEnum.PROCESSING.getCode());
        repair.setStartTime(new Date());
        repairMapper.updateById(repair);

        // 记录状态变更日志
        recordStatusLog(workOrderId, RepairStatusEnum.PENDING.getCode(),
                RepairStatusEnum.PROCESSING.getCode(), processorId, "开始处理");

        return true;
    }

    @Override
    public boolean completeWorkOrder(String workOrderId, String processorId, String notes, String images) {
        // 查询工单
        EquipmentRepair repair = getWorkOrderById(workOrderId);

        // 验证工单状态（只能处理中的工单才能完成）
        if (!repair.getRepairResult().equals(RepairStatusEnum.PROCESSING.getCode())) {
            throw new RuntimeException("工单状态不是处理中，无法完成");
        }

        // 更新状态、结束时间和备注
        repair.setRepairResult(RepairStatusEnum.COMPLETED.getCode());
        repair.setEndTime(new Date());
        repair.setRepairNotes(notes);
        repair.setRepairImages(images);
        repairMapper.updateById(repair);

        // 记录状态变更日志
        recordStatusLog(workOrderId, RepairStatusEnum.PROCESSING.getCode(),
                RepairStatusEnum.COMPLETED.getCode(), processorId, "处理完成：" + notes);

        return true;
    }

    @Override
    public boolean markWorkOrderFailed(String workOrderId, String processorId, String failureReason) {
        // 查询工单
        EquipmentRepair repair = getWorkOrderById(workOrderId);

        // 验证工单状态（处理中的工单才能标记失败）
        if (!repair.getRepairResult().equals(RepairStatusEnum.PROCESSING.getCode())) {
            throw new RuntimeException("工单状态不是处理中，无法标记失败");
        }

        // 更新状态、结束时间和备注
        repair.setRepairResult(RepairStatusEnum.FAILED.getCode());
        repair.setEndTime(new Date());
        repair.setRepairNotes(failureReason);
        repairMapper.updateById(repair);

        // 记录状态变更日志
        recordStatusLog(workOrderId, RepairStatusEnum.PROCESSING.getCode(),
                RepairStatusEnum.FAILED.getCode(), processorId, "处理失败：" + failureReason);

        return true;
    }

    @Override
    public WorkOrderDetailVO getWorkOrderDetail(String workOrderId) {
        // 查询工单
        EquipmentRepair repair = getWorkOrderById(workOrderId);

        // 查询关联的故障信息
        FaultAnalysis fault = faultMapper.selectById(repair.getAnomalyId());

        // 转换为VO
        WorkOrderDetailVO vo = new WorkOrderDetailVO();
        BeanUtils.copyProperties(repair, vo);
        vo.setFaultId(fault.getId());
        vo.setStatusDesc(RepairStatusEnum.valueOf(repair.getRepairResult()).getDesc());
        vo.setPriorityDesc(RepairPriorityEnum.valueOf(repair.getPriority()).getDesc());

        return vo;
    }

    @Override
    public Page<WorkOrderListVO> listWorkOrders(Integer status, Integer pageNum, Integer pageSize, Integer processorId) {
        System.out.println("[筛选工单] 接收的status参数: " + status); // 添加日志
        // 构建查询条件
        QueryWrapper<EquipmentRepair> queryWrapper = new QueryWrapper<>();
        if (status != null) {
            System.out.println("[筛选工单] 添加status条件: " + status); // 添加日志
            queryWrapper.eq("repair_result", status);
        }
        if (processorId != null) {
            System.out.println("[筛选工单] 添加processorId条件: " + processorId);
            queryWrapper.eq("processor_id", processorId); // 假设数据库字段名为processor_id
        }
        queryWrapper.orderByDesc("create_time");

        // 分页查询
        Page<EquipmentRepair> page = new Page<>(pageNum, pageSize);
        Page<EquipmentRepair> resultPage = repairMapper.selectPage(page, queryWrapper);

        // 转换为VO
        Page<WorkOrderListVO> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        List<WorkOrderListVO> voList = resultPage.getRecords().stream().map(repair -> {
            WorkOrderListVO vo = new WorkOrderListVO();
            BeanUtils.copyProperties(repair, vo);
            vo.setStatusDesc(RepairStatusEnum.valueOf(repair.getRepairResult()).getDesc());
            vo.setPriorityDesc(RepairPriorityEnum.valueOf(repair.getPriority()).getDesc());

            // 查询关联的故障信息（只取必要字段）
            FaultAnalysis fault = faultMapper.selectOne(
                    new QueryWrapper<FaultAnalysis>().select("id", "fault_type", "analysis_time")
                            .eq("id", repair.getAnomalyId())
            );
            vo.setFaultId(fault.getId());
            vo.setFaultType(fault.getFaultType());
            vo.setFaultTime(fault.getAnalysisTime());

            return vo;
        }).collect(Collectors.toList());

        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public List<WorkOrderStatusLogVO> getStatusHistory(String workOrderId) {
        // 查询状态变更历史
        List<RepairStatusLog> logs = logMapper.selectList(
                new QueryWrapper<RepairStatusLog>().eq("repair_id", workOrderId)
                        .orderByAsc("operate_time")
        );

        // 转换为VO
        return logs.stream().map(log -> {
            WorkOrderStatusLogVO vo = new WorkOrderStatusLogVO();
            BeanUtils.copyProperties(log, vo);

            // 安全获取枚举描述
            RepairStatusEnum oldStatusEnum = RepairStatusEnum.valueOf(log.getOldStatus());
            RepairStatusEnum newStatusEnum = RepairStatusEnum.valueOf(log.getNewStatus());

            vo.setOldStatusDesc(oldStatusEnum != null ? oldStatusEnum.getDesc() : "未知状态");
            vo.setNewStatusDesc(newStatusEnum != null ? newStatusEnum.getDesc() : "未知状态");

            return vo;
        }).collect(Collectors.toList());
    }

    // 私有方法：获取工单并校验存在性
    private EquipmentRepair getWorkOrderById(String workOrderId) {
        EquipmentRepair repair = repairMapper.selectByRepairId(workOrderId);
        if (repair == null) {
            throw new RuntimeException("工单不存在");
        }
        return repair;
    }

    // 私有方法：记录状态变更日志
    private void recordStatusLog(String workOrderId, Integer oldStatus, Integer newStatus,
                                 String operatorId, String remark) {
        RepairStatusLog log = new RepairStatusLog();
        log.setRepairId(workOrderId);
        log.setOldStatus(oldStatus);
        log.setNewStatus(newStatus);
        log.setOperatorId(operatorId);
        log.setRemark(remark);
        log.setOperateTime(new Date());
        logMapper.insert(log);
    }
}
